"""Celery tasks for music generation."""
from celery_app import celery
from app import create_app, db
from app.services.ai_generation_service import AIGenerationService
from app.services.storage_service import StorageService
from app.models.music import Music
from config import config
from datetime import datetime


class SimplePOI:
    """Simple POI object for AI generation (not a database model)."""
    def __init__(self, data):
        self.id = data.get('id')
        self.name = data.get('name')
        self.category = data.get('category')
        self.description = data.get('description', '')
        location = data.get('location', {})
        self.latitude = location.get('latitude') if isinstance(location, dict) else data.get('latitude')
        self.longitude = location.get('longitude') if isinstance(location, dict) else data.get('longitude')


class SimpleWeather:
    """Simple Weather object for AI generation (not a database model)."""
    def __init__(self, data):
        self.temperature = data.get('temperature')
        self.condition = data.get('condition')
        self.humidity = data.get('humidity')
        self.wind_speed = data.get('wind_speed')
        self.aqi = data.get('aqi')
        timestamp_str = data.get('timestamp')
        self.timestamp = datetime.fromisoformat(timestamp_str) if timestamp_str else datetime.utcnow()


@celery.task(name='tasks.generate_and_save_music')
def generate_and_save_music(
    user_id: str,
    session_id: str,
    poi_data: dict,
    weather_data: dict,
    mood: str
) -> dict:
    """Generate background music and save to database.
    
    This is an async Celery task that:
    1. Generates music using AI
    2. Uploads to OSS
    3. Saves metadata to database
    
    Args:
        user_id: User ID
        session_id: Walking session ID
        poi_data: POI data as dict
        weather_data: Weather data as dict
        mood: Mood/atmosphere
        
    Returns:
        Dict with music_id and file_url
    """
    # Create Flask app context for database operations
    app = create_app()
    cfg = config['default']
    
    with app.app_context():
        try:
            # Create simple POI and Weather objects for AI generation
            poi = SimplePOI(poi_data)
            weather = SimpleWeather(weather_data)
            
            # Initialize services
            ai_service = AIGenerationService(
                api_key=cfg.OPENAI_API_KEY,
                api_base=cfg.OPENAI_API_BASE
            )
            
            storage_service = StorageService(
                endpoint=cfg.OSS_ENDPOINT,
                access_key_id=cfg.OSS_ACCESS_KEY_ID,
                access_key_secret=cfg.OSS_ACCESS_KEY_SECRET,
                bucket_name=cfg.OSS_BUCKET_NAME
            )
            
            # Generate music
            audio_bytes = ai_service.generate_background_music(
                poi=poi,
                weather=weather,
                mood=mood,
                suno_api_key=cfg.SUNO_API_KEY
            )
            
            # Upload to OSS
            file_url = storage_service.upload_audio(audio_bytes)
            
            # Save to database
            music = Music(
                user_id=user_id,
                session_id=session_id,
                poi_id=poi_data.get('id'),
                file_url=file_url,
                duration=60,  # Default 60 seconds
                meta_info={
                    'poi_name': poi.name,
                    'weather': weather_data,
                    'mood': mood,
                    'generated_at': datetime.utcnow().isoformat()
                }
            )
            
            db.session.add(music)
            db.session.commit()
            
            return {
                'success': True,
                'music_id': music.id,
                'file_url': file_url
            }
            
        except Exception as e:
            db.session.rollback()
            return {
                'success': False,
                'error': str(e)
            }
